<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="../../css/public.css" media="all">
    <link rel="stylesheet" href="../../lib/yzhUpload/control/css/zyUpload.css" type="text/css">
    <style>
        body {
            background-color: #ffffff;
        }

        .aui-upload-box {
            background-color: #fff;
            width: 105px;
            height: 105px;
            padding-top: 5px;
            padding-right: 5px;
        }

        .chose_pic_btn {
            width: 95px;
            height: 95px;
            position: relative;
            display: inline-block;
            background-image: url('');
            box-sizing: border-box;
            background-size: 45px 45px;
            background-position: center center;
            background-repeat: no-repeat;
            background-color: #ededed;
            margin-left: 3.3333%;
            margin-bottom: 12px;
            border-radius: 5px;
        }

        .chose_pic_btn div {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0;
            width: 100%;
            height: 100%;
        }

        .cancel {
            width: 20px;
            height: 20px;
            line-height: 19px;
            border: 1px solid #dbd9d9;
            background-color: #dbd9d9;
            border-radius: 50%;
            position: absolute; /* 父组件赋予属性relative生效 */
            right: 0px; /* 使元素处于右上角-右 */
            top: 0px; /* 使元素处于右上角-上 */
        }

        .cancel::before,
        .cancel::after {
            content: "";
            position: absolute;
            height: 14px;
            width: 2px;
            top: 3px; /* 使X处于圆中心 */
            left: 9px; /* 使X处于圆中心 */
            background-color: #353535;
        }

        .cancel::before {
            transform: rotate(45deg);
        }

        .cancel::after {
            transform: rotate(-45deg);
        }

        .layui-form-select dl {
            top: auto;
            bottom: 36px;
        }

        .zyupload {
            height: auto !important;
        }

        .layui-table th {
            text-align: center;
        }

        .layui-table td {
            text-align: center;
        }

        .layui-select-dropdown {
            top: auto !important;
            bottom: 100% !important;
        }
    </style>
</head>
<body>
<div class="layui-form layuimini-form">
    <div class="layui-form-item">
        <label class="layui-form-label required">课程标题</label>
        <div class="layui-input-block">
            <input type="text" name="title" lay-verify="required" lay-reqtext="视频标题不能为空" placeholder="请填写视频标题" value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">缩略图</label>
        <div class="layui-input-block">
            <div class="layui-upload">
                <div class="aui-upload-box">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn" id="mainDiagram">
						<div>
                        </div>
					</span>
                    </div>
                </div>
                <p id="errText"></p>
                <button type="button" class="layui-btn" id="upload-mainDiagram">上传图片</button>
                <!--<div class="layui-upload-list">-->
                <!--    <img style="width: 95px" class="layui-upload-img" id="mainDiagram">-->
                <!--    <p id="errText"></p>-->
                <!--</div>-->
            </div>
            <input type="text" style="display: none" name="mainDiagram" lay-verify="required" placeholder="请输入缩略图链接"
                   value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">关键字</label>
        <div class="layui-input-block">
            <div id="tagsId"></div>
            <input type="text" name="tags" value="" lay-verify="required" hidden>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">课程分类</label>
        <div class="layui-input-inline">
            <select class="lay-select-search" id="level-1-category" lay-filter="levelOneCategory"></select>
        </div>
        <div class="layui-input-inline">
            <select class="lay-select-search" id="level-2-category" lay-filter="levelTwoCategory"></select>
        </div>
        <input type="text" name="category" value="" hidden>
        <input type="text" name="categoryId" value="" hidden>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">课程属性</label>
        <div class="layui-input-block">
            <input type="radio" name="type" lay-filter="type" value="0" title="视频课程" checked>
            <input type="radio" name="type" lay-filter="type" value="1" title="图文课程">
        </div>
    </div>
    <div class="layui-form-item video_course">
        <label class="layui-form-label">课程链接</label>
        <div class="layui-input-block">
            <input id="videoUrl" type="text" name="videoUrl" lay-reqtext="课程链接不能为空"
                   placeholder="请填写课程链接"
                   value=""
                   class="layui-input">
            <input style="display: none" type="text" name="videoDuration" lay-reqtext="课程链接不能为空"
                   placeholder="视频时长"
                   value=""
                   class="layui-input">
        </div>
    </div>
    <div class="layui-form-item image_course" style="display: none">
        <label class="layui-form-label">课程主图</label>
        <div class="layui-input-block">
            <div style="display: flex;flex-wrap: wrap">
                <div id="ad-images" style="display: flex;flex-wrap: wrap"></div>
                <div class="aui-upload-box" onclick="addBusinessLicense()">
                    <div class="aui-upload-pic">
					<span class="chose_pic_btn">
						<div></div>
					</span>
                    </div>
                </div>
            </div>
            <div id="zy-upload" class="zyupload"></div>
            <input type="text" name="graphicUrl" value="" hidden>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">课程售价</label>
        <div class="layui-input-block">
            <input type="text" name="price" placeholder="请填写视频价格" value="0" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">所属企业/工作室</label>
        <div class="layui-input-block">
            <input type="text" name="enterpriseName" placeholder="请输入所属企业/工作室" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">联系人</label>
        <div class="layui-input-block">
            <input type="text" name="contactUser" placeholder="请填写联系人" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">联系方式</label>
        <div class="layui-input-block">
            <input type="text" name="phone" placeholder="请填写联系方式" value="" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">课程简介</label>
        <div class="layui-input-block">
            <div id="editor" style="margin: 0px 0 5px 0"></div>
            <button class="layui-btn layui-btn-danger" onclick="emptyDetails()">清除简介</button>
            <input type="text" name="description" value="" hidden>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认发布</button>
        </div>
    </div>
</div>
<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="../../lib/common/common.js" charset="utf-8"></script>
<script src="../../lib/common/commonApi.js" charset="utf-8"></script>
<script src="../../lib/jquery-3.4.1/jquery-3.4.1.min.js" charset="utf-8"></script>
<script src="../../js/lay-module/xm-select-master/dist/xm-select.js" charset="utf-8"></script>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<script type="text/javascript" src="../../lib/yzhUpload/core/zyFile.js"></script>
<script type="text/javascript" src="../../lib/yzhUpload/control/js/zyUpload.js"></script>
<script>

    let cacheVideoUrl = ''
    let editor;
    window.onload = function () {
        $("#zy-upload").zyUpload({
            width: "650px",                 // 宽度
            height: "400px",                 // 宽度
            itemWidth: "120px",                 // 文件项的宽度
            itemHeight: "100px",                 // 文件项的高度
            url: "/upload/UploadAction",  // 上传文件的路径
            multiple: true,                    // 是否可以多个文件上传
            dragDrop: true,                    // 是否可以拖动上传文件
            del: true,                    // 是否可以删除文件
            finishDel: false,  				  // 是否在上传文件完成后删除预览
            /* 外部获得的回调接口 */
            onSelect: function (files, allFiles) {                    // 选择文件的回调方法
                console.info("当前选择了以下文件：");
                console.info(files);
                console.info("之前没上传的文件：");
                console.info(allFiles);
            },
            onDelete: function (file, surplusFiles) {                     // 删除一个文件的回调方法
                console.info("当前删除了此文件：");
                console.info(file);
                console.info("当前剩余的文件：");
                console.info(surplusFiles);
            },
            onSuccess: function (file, response) {                    // 文件上传成功的回调方法
                console.info("此文件上传成功：");
                if (isNotNull(response.url)) {
                    uploadAddToImg(response.url);
                }
            },
            onFailure: function (file) {                    // 文件上传失败的回调方法
                console.info("此文件上传失败：");
                console.info(file);
            },
            onComplete: function (responseInfo) {           // 上传完成的回调方法
                console.info("文件上传完成");
                console.info(responseInfo);
            }
        });
    }

    //常规使用 - 普通图片上传
    layui.use(['layer'], function () {
        var upload = layui.upload,
            $ = layui.$;
        let uploadInst = upload.render({
            elem: '#upload-mainDiagram'
            , url: '/meily/upload'
            , before: function (obj) {
                //预读本地文件示例，不支持ie8
                obj.preview(function (index, file, result) {
                    $('#mainDiagram').css({
                        'background-image': 'url(' +result + ')',
                        'background-size': '100% 100%'
                    }); //图片链接（base64）
                });
                layer.msg('上传中', {icon: 16, time: 0});
            }
            , done: function (res) {
                //如果上传失败
                if (res.code !== '200') {
                    return layer.msg('上传失败');
                }
                //上传成功的一些操作
                $('input[name="mainDiagram"]').val(res.url);
                $('#errText').html(''); //置空上传失败的状态
            }
            , error: function () {
                //演示失败状态，并实现重传
                var demoText = $('#errText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs upload-reload" style="margin-bottom: 5px">重试</a>');
                demoText.find('.upload-reload').on('click', function () {
                    uploadInst.upload();
                });
            }
            //进度条
            , progress: function (n, elem, e) {
                if (n == 100) {
                    layer.msg('上传完毕', {icon: 1});
                }
            }
        });
    });

    layui.use(['layer', 'form', 'layarea'], function () {
        var form = layui.form,
            layer = layui.layer,
            layarea = layui.layarea,
            $ = layui.$;

        layarea.render({
            elem: '#area-picker',
            data: {},
            change: function (res) {
                //选择结果
                let area = res.province + "-" + res.city;
                $('input[name="area"]').val(area);
            }
        });

        // 监听公告类型单选框
        form.on('radio(type)', function (data) {
            var type = data.value;
            if (type === '0') {
                $('.video_course').show();
                $('.image_course').hide();
            } else if (type === '1') {
                $('.video_course').hide();
                $('.image_course').show();
            }
        });


        $("#videoUrl").blur(function () {
            // 解析视频链接
            let videoUrl = $("#videoUrl").val();
            if (isNotNull(videoUrl)) {
                if (cacheVideoUrl === videoUrl) {
                    return;
                }
                // 解析视频
                let myMsg = layer.msg("正在解析视频。。。", {
                    icon: 16,
                    time: -1
                })
                let video = document.createElement('video');
                // 等待视频元数据加载完成后执行
                video.addEventListener('loadedmetadata', function () {
                    let duration = video.duration
                    $('input[name="videoDuration"]').val(Math.floor(duration));
                    if (duration) {
                        cacheVideoUrl = videoUrl;
                        layer.close(myMsg);//手动关闭
                    }
                });
                video.addEventListener('error', function () {
                    layer.msg("该链接指向资源不为视频资源，请重新输入视频链接");//手动关闭
                    $('#videoUrl').val('');
                    setTimeout(function () {
                        layer.close(myMsg);//手动关闭
                    }, 1500);
                });
                video.src = videoUrl;
                video.load();
            }
        })

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            var index = layer.alert("确定提交吗？", {
                title: '提示'
            }, function () {
                if (!isNotNull(data.field.videoUrl) && !isNotNull(data.field.graphicUrl)){
                    layer.msg("请录入课程链接或课程主图");
                    return;
                }
                let myMsg = layer.msg("正在提交...", {
                    icon: 16,
                    time: -1
                })
                $.ajax({
                    type: "post",
                    url: '/learning/course/add',
                    data: JSON.stringify(data.field),
                    dataType: 'json',
                    contentType: 'application/json; charset=UTF-8',
                    success: function (req) {
                        if (req.code === '200') {
                            layer.msg("已添加");
                            layer.close(index);
                            // 关闭弹出层
                            setTimeout(function () {
                                layer.close(myMsg);//手动关闭
                                let iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                                // 调用父页面的方法
                                let parentWindow = window.parent;
                                parentWindow.reloadTable();
                            }, 1500);
                        } else {
                            layer.msg(req.msg);
                        }
                    },
                    error: function (e) {
                        layer.msg("添加失败");
                        layer.close(myMsg);//手动关闭
                    }
                })

            });

            return false;
        });

    });

    // 初始化 课程分类下拉列表
    layui.use(['form', 'layer', 'jquery'], function () {
        var form = layui.form,
            layer = parent.layer === undefined ? layui.layer : parent.layer,
            $ = layui.jquery;
        let levelOneCategoryText = "";
        let levelTwoCategoryText = "";

        //异步加载下拉框数据
        let res = getCourseCategoryList('0')
        res.then((list) => {
            if (list.length === 0) {
                return;
            }
            let $html = "";
            $html += "<option value=''>" + '请选择分类' + "</option>";
            for (const index in list) {
                $html += "<option value='" + list[index].id + "'>" + list[index].name + "</option>";
            }
            $("#level-1-category").append($html);
            form.render('select');
        })

        // 监听品类下拉框
        form.on('select(levelOneCategory)', function (dataObj) {
            $("#level-2-category").empty();
            let classesHtml = '<option value="">请选择</option>';
            $("#level-2-category").html(classesHtml);
            levelOneCategoryText = $("#level-1-category").find("option:selected").text();
            let value = $("#level-1-category").val();
            $('input[name="category"]').val(levelOneCategoryText);
            $('input[name="categoryId"]').val(value);
            //异步加载下拉框数据
            if (!isNotNull(value)) {
                $('input[name="category"]').val('');
                $('input[name="categoryId"]').val('');
                return;
            }
            let res = getCourseCategoryList(value)
            res.then((list) => {
                if (list.length === 0) {
                    return;
                }
                let $html = "";
                for (const index in list) {
                    $html += "<option value='" + list[index].id + "'>" + list[index].name + "</option>";
                }
                $("#level-2-category").append($html);
                form.render('select');
            })
        });
        //监听类目下拉框
        form.on('select(levelTwoCategory)', function (dataObj) {
            levelTwoCategoryText = $("#level-2-category").find("option:selected").text();
            let value = $("#level-2-category").val();
            let categoryText = levelOneCategoryText + "-" + levelTwoCategoryText;
            $('input[name="category"]').val(categoryText);
            $('input[name="categoryId"]').val(value);
        });

    });

    // // 初始化企业列表
    // layui.use(['form', 'layer', 'jquery'], function () {
    //     var form = layui.form,
    //         layer = parent.layer === undefined ? layui.layer : parent.layer,
    //         $ = layui.jquery;
    //     let enterpriseName = ''
    //     let res = getEnterpriseList();
    //     res.then(list => {
    //         if (list.length === 0) {
    //             return;
    //         }
    //         let $html = "";
    //         for (const index in list) {
    //             $html += "<option value='" + list[index].enterpriseNo + "'>" + list[index].enterpriseName + "</option>";
    //         }
    //         $("#enterprise").append($html);
    //         form.render('select');
    //     })
    //     form.on('select(enterprise)', function (dataObj) {
    //         enterpriseName = $("#enterprise").find("option:selected").text();
    //         let value = $("#enterprise").val();
    //         if (!isNotNull(value)) {
    //             enterpriseName = '';
    //         }
    //         $('input[name="enterpriseName"]').val(enterpriseName);
    //     });
    // })

    let xm_select = xmSelect.render({
        el: '#tagsId',
        language: 'zn',
        direction: 'down',
        data: [],
        on: function (data) {
            let tags = ''
            if (isNotNull(data.arr) && data.arr.length > 0) {
                for (const i in data.arr) {
                    if (tags == '') {
                        tags = data.arr[i].value
                    } else {
                        tags += "," + data.arr[i].value
                    }
                }
            }
            $('input[name="tags"]').val(tags);
        },
        filterable: true,
        create: function (val, arr) {
            //返回一个创建成功的对象, val是搜索的数据, arr是搜索后的当前页面数据
            return {
                name: val,
                value: val
            }
        }
    })

    //富文本编辑器
    layui.use(['layer', 'wangEditor'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            wangEditor = layui.wangEditor;

        editor = new wangEditor('#editor');
        editor.customConfig.uploadImgServer = "/meily/upload";
        editor.customConfig.uploadFileName = 'file';
        editor.customConfig.pasteFilterStyle = false;
        editor.customConfig.uploadImgMaxLength = 5;
        editor.customConfig.uploadImgHooks = {
            // 上传超时
            timeout: function (xhr, editor) {
                layer.msg('上传超时！')
            },
            // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式，可使用该配置
            customInsert: function (insertImg, result, editor) {
                console.log(result);
                if (result.code == 200) {
                    var url = result.url;
                    insertImg(url);
                    // url.forEach(function (e) {
                    //     insertImg(e);
                    // })
                } else {
                    layer.msg(result.msg);
                }
            }
        };
        editor.customConfig.customAlert = function (info) {
            layer.msg(info);
        };
        editor.customConfig.onchange = function (html) {
            $('input[name="description"]').val(html);
        };
        editor.create();
    });

    /**
     * 清空商品详情（包括源代码）
     */
    function emptyDetails() {
        editor.txt.clear();
        $('input[name="description"]').val('');
        layui.use(['layer'], function () {
            let $ = layui.$, layer = layui.layer;
            layer.msg("已清除！")
        })
    }

    /**
     * 上传图片
     */
    function addBusinessLicense() {
        layui.use(['layer', 'form'], function () {
            const layer = layui.layer
            layer.prompt({
                title: '请输入图片链接',
                btn: ['确定', '取消'],
                area: ['200px', '20px'],
                formType: 0
            }, function (text, index) {
                const input = text.trim();
                if (input) {
                    let images = $('input[name="graphicUrl"]').val();
                    const newImages = images ? `${images},${input}` : input;
                    $('input[name="graphicUrl"]').val(newImages);
                    renderImages(newImages);
                } else {
                    layer.msg("图片链接不能为空噢");
                }
                layer.close(index);
            });
        });
    }

    /**
     * 渲染加载的图片
     */
    function renderImages(imageLink) {
        let adImages = $("#ad-images");  // 缓存目标元素
        adImages.empty();  // 清空目标元素
        if (!imageLink) return;  // 如果参数为空或undefined则直接返回
        const imgsArr = imageLink.split(",");  // 将参数字符串分割成图片链接数组
        const html = imgsArr.map((link, index) => {  // 构建HTML代码
            const div = $("<div>").css({  // 创建div元素并设置样式和属性
                padding: "5px 10px 15px 0px",
                position: "relative",
                width: "95px",
                height: "95px"
            });
            const img = $("<img>").attr({  // 创建img元素并设置样式和属性
                width: "95px",
                height: "95px",
                src: link
            });
            const span = $("<span>").addClass("cancel").on("click", () => delImage(index));  // 创建span元素并设置样式和事件处理器
            return div.append(img).append(span);  // 将img和span添加到div中并返回div元素
        });  // 将jQuery对象转换成DOM元素数组
        // const div = $("<div>").css({  // 创建div元素并设置样式和属性
        //     padding: "5px 10px 15px 0px",
        //     position: "relative",
        //     width: "95px",
        //     height: "95px"
        // });
        // const img = $("<img>").attr({  // 创建img元素并设置样式和属性
        //     width: "95px",
        //     height: "95px",
        //     src: imageLink
        // });
        // const span = $("<span>").addClass("cancel").on("click", () => delImage(0));  // 创建span元素并设置样式和事件处理器
        // const html = div.append(img).append(span);
        $('input[name="graphicUrl"]').val(imageLink);
        adImages.html(html);  // 将HTML代码添加到目标元素中
    }

    /**
     * 删除图片
     */
    function delImage(index) {
        const businessLicenseInput = $('input[name="graphicUrl"]');  // 缓存目标输入框
        let imageLinks = businessLicenseInput.val();  // 获取目标输入框的值
        if (!imageLinks) return;  // 如果目标输入框的值为空，则直接返回
        const imgsArr = imageLinks.split(",");  // 将图片链接字符串分割成数组
        const newImageLinks = imgsArr.filter((link, i) => i !== index).join(",");  // 过滤掉指定下标的图片链接并拼接成新的图片链接字符串
        businessLicenseInput.val(newImageLinks);  // 将新的图片链接字符串设置为目标输入框的值
        renderImages(newImageLinks);  // 重新生成图片预览
    }

    /**
     * 上传文件完成后将文件地址添加到图片列表中
     * @param url
     */
    function uploadAddToImg(url) {
        const businessLicenseInput = $('input[name="graphicUrl"]'); // 缓存目标输入框
        let images = businessLicenseInput.val() ?? ''; // 获取目标输入框的值
        if (isNotNull(url)) {
            images = `${images ? images + ',' : ''}${url}`; // 使用模板字符串简化字符串的拼接
            businessLicenseInput.val(images); // 将新的图片链接字符串设置为目标输入框的值
            renderImages(images); // 重新生成图片预览
        }
        // renderImages(url); // 重新生成图片预览
    }

    function formatTime(seconds) {
        const hours = Math.floor(seconds / 3600);
        const minutes = Math.floor((seconds % 3600) / 60);
        const remainingSeconds = seconds % 60;

        if (hours > 0) {
            return `${hours}小时${minutes}分钟${remainingSeconds}秒`;
        } else if (minutes > 0) {
            return `${minutes}分钟${remainingSeconds}秒`;
        } else {
            return `${remainingSeconds}秒`;
        }
    }
</script>
</body>
</html>
